
import SdkConf from "./SdkConf";
import EventCenter from "./EventCenter";




/**author:yebinx email:yebinx@21cm.com*/
export default class Sdk{
    private static _sdk:Sdk;
    public sdkEnvironment:any;
    public bannerAd=null;
    public rewardedVideoAd=null;
    
    public wxSound=null;
    public boxAd=null;
    public gameRecorder=null;
    public hideTime:number=0;
    private mStartRecordTime:number=0;
    private mVideoPath:string="";
   private plafrom:string="web";
   private lookVideoTime:number=0;
   private videoTimeLimit:number=0;
    constructor(){
        this.sdkEnvironment=this.getSdkEnvironment();
        if(this.sdkEnvironment){
            if(Laya.Browser.onMiniGame){
                Laya.Browser.window.wx.showShareMenu({
                    withShareTicket: true,
					 menus: ['shareAppMessage', 'shareTimeline']
                  });
                  let self = this;
                Laya.Browser.window.wx.onShareAppMessage(function () {
					EventCenter.getIns().event("onShareAppMessage");
                    return {
                        title: SdkConf.shareDes,
                      imageUrlId: SdkConf.shareImgId,
                      imageUrl: SdkConf.shareImgUrl
                    }
                  })
				if(this.sdkEnvironment.onShareTimeline)this.sdkEnvironment.onShareTimeline(()=>{
					EventCenter.getIns().event("onShareTimeline");
				               return {
				                   title:SdkConf.shareDes,
				                   imageUrl:SdkConf.shareImgId,
				                   query:"a=1&b=2"
				               }
				});
            }
			
			
    
            this.sdkEnvironment.onShow((res)=>{//	scene query
                    EventCenter.getIns().event("onShow");
              });
    
              this.sdkEnvironment.onHide(()=>{
                EventCenter.getIns().event("onHide");
                this.hideTime=new Date().getTime();
              });
			  
			  this.createBoxAd();
        }
        if(this.gameRecorder){
            this.gameRecorder.onStart(res => {
                console.log("头条 录屏开始");
                this.mStartRecordTime=new Date().getTime();
            })

            this.gameRecorder.onStop((res) => {
                console.log("recording onstop!!")
                this.mVideoPath=res.videoPath;
            })
    
        }
        
    }

    public getEnterOptionsSync(){
        if(Laya.Browser.onMiniGame){
            return Laya.Browser.window.wx.getEnterOptionsSync();//scene 	query
        }
    }

   
    public sendWxMsg(data){
        if(Laya.Browser.onMiniGame){
            Laya.Browser.window.wx.getOpenDataContext().postMessage(data);
        }
    }

      /**
         * 上报自己的数据
         * @param data 上报数据
         */
    public setUserCloudStorage(data):void{
        if(Laya.Browser.onMiniGame){
            var kvDataList = [];
            kvDataList.push({"key":SdkConf.setUserCloudStorageKey,"value":JSON.stringify(data)});
            Laya.Browser.window.wx.setUserCloudStorage({
                KVDataList:kvDataList,
                success:function(e):void{
                    console.log('-----success:' + JSON.stringify(e));
                },
                fail:function(e):void{
                    console.log('-----fail:' + JSON.stringify(e));
                },
                complete:function(e):void{
                    console.log('-----complete:' + JSON.stringify(e));
                }
            });
        }
    }
    
    private videoFunc:Function;
    public showAd(call){
        this.videoFunc=call;
		if(this.videoTimeLimit){
			let time = new Date().getTime();
			if(time-this.lookVideoTime<this.videoTimeLimit){
				this.videoFunc(3);
				return;
			}
			this.lookVideoTime=time;
			
		}
        var adUnitId=SdkConf.getVideoId(this.plafrom);
        if(!this.sdkEnvironment){
            this.videoFunc(0);
            return;
        }
        if(!adUnitId){
            this.videoFunc(4);
            return; 
        }
        if(!this.rewardedVideoAd){
            this.rewardedVideoAd =this.sdkEnvironment.createRewardedVideoAd({adUnitId: adUnitId})
            this.rewardedVideoAd.onError(res =>{
                this.videoFunc(2);
            });
            this.rewardedVideoAd.onClose(res => {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                if (res && res.isEnded || res === undefined) {
                  // 正常播放结束，可以下发游戏奖励
                  EventCenter.getIns().event("videoSucess");
                  this.videoFunc(0);
                } else {
                  // 播放中途退出，不下发游戏奖励
                  this.videoFunc(1);
                }
              })
            
        }
        this.rewardedVideoAd.show()
        .catch(err => {
            this.rewardedVideoAd.load()
            .then(() => this.rewardedVideoAd.show())
        })
    }
    
    public showBanner(_w:number=600,_y:number=970,_isButtom:boolean=true){
        if(!this.sdkEnvironment)return;
        let adUnitId=SdkConf.getBannerId(this.plafrom);
        if(!adUnitId)return;
        var x = 20, y = _y, w = _w;
        var info = this.sdkEnvironment.getSystemInfoSync();
        var sx = info.windowWidth / Laya.stage.width;
        var sy = info.windowHeight / Laya.stage.height;
        var ws = w * sx;
        if(ws<300)ws=300;
        else if(ws>Laya.stage.height-20)ws=Laya.stage.height-20;
        var xs = (Laya.stage.width * sx - ws) / 2;
        var ys = _y * sy;
        var s = 20;
        var tleft = xs //- ws / 2 + s / 2;
        var twid = ws //- s;
        if(Laya.Browser.onQGMiniGame){
            tleft=0;
            twid=info.windowWidth;
            ys=null;
        }
        let tsty:any ={
            left: tleft,
            top: ys,
            width: twid,
          }
          if(_isButtom){
            tsty.top=null;
            tsty.bottom=4;
          }
        if (!this.bannerAd) {
            if(Laya.Browser.onQGMiniGame){
                this.bannerAd = this.sdkEnvironment.createBannerAd({
                  posId: adUnitId,
                  style: tsty
                })
            }else if(Laya.Browser.onMiniGame || Laya.Browser.onQQMiniGame){
                this.bannerAd = this.sdkEnvironment.createBannerAd({
                    adUnitId: adUnitId,
                    style: tsty
                  })
            }
            this.bannerAd.onError(function(res)  {
                //this.test("showBannerErr",res);
                if(this.bannerErrTimes<3)this.bannerAd.show();
                this.bannerErrTimes++;
            })
            if(this.bannerAd.onShow){
                this.bannerAd.onShow(function() {
                    this.bannerErrTimes=0;
                })
            }
			 let treziedMethed:string="onResize";
             if(this.plafrom== "vivo")treziedMethed="onSize"
             if(this.bannerAd[treziedMethed]){
                 this.bannerAd[treziedMethed]((res)=>{
                     //console.log("bannerAd.onResize:"+JSON.stringify(res));
                     if(_isButtom && res.height){
                         let ttop:number=info.windowHeight-res.height;
                         if(this.bannerAd.style){
                             if(this.bannerAd.style.top!=ttop){
                                 this.bannerAd.style.left=(info.windowWidth-res.width)/2;
                                 this.bannerAd.style.top=ttop;
                             }
                         }else if(this.bannerAd.y){
                             this.bannerAd.x=(info.windowWidth-res.width)/2;
                             this.bannerAd.y=ttop;
                         }else if(this.bannerAd.top){
                             this.bannerAd.left=(info.windowWidth-res.width)/2;
                             this.bannerAd.top=ttop;
                         }
                     }
                 })
             }
        }
        this.bannerAd.show();
    }
    public hideBanner(_dispose:boolean=true){
        if(this.bannerAd){
            this.bannerAd.hide();
            this.bannerAd.destroy();
            this.bannerAd=null;
        }
    }

    private interstitialAd;
    public showInterstitialAd(){
        let tadUnitId=SdkConf.getInsertId(this.plafrom);
        if (this.sdkEnvironment && this.sdkEnvironment.createInterstitialAd && tadUnitId){
            this.interstitialAd = this.sdkEnvironment.createInterstitialAd({
              adUnitId: tadUnitId
            })
          }

          if ( this.interstitialAd) {
            this.interstitialAd.show();
          }
    }

    public createBoxAd(_style?:any){
        if (!this.sdkEnvironment) return;
        let adUnitId = SdkConf.getBoxAdId(this.plafrom);
        if (!adUnitId) return;
        if(!this.boxAd){
			if(this.plafrom=="qq"){
				this.boxAd = this.sdkEnvironment.createAppBox({adUnitId:adUnitId});
				this.boxAd.onClose(function(){
					EventCenter.getIns().event("boxAdClose");
				});	
				this.boxAd.load();
			}else if(this.plafrom=="wx"){
				var info = this.sdkEnvironment.getSystemInfoSync();
				var sx = info.windowWidth / Laya.stage.width;
				var sy = info.windowHeight / Laya.stage.height;
				let tstlye = _style?_style:{left: 10,top: 400,width: 600};
				let tdata={adUnitId:adUnitId,adIntervals: 30,style: {left: tstlye.left*sx,top: tstlye.top*sy,width: tstlye.width*sx}};
				this.boxAd = this.sdkEnvironment.createGridAd(tdata);
			}
        }
        
    }

    public showBoxAd(_style?:any){
        if(this.boxAd){
			this.boxAd.show();
			if(_style){
				var info = this.sdkEnvironment.getSystemInfoSync();
				var sx = info.windowWidth / Laya.stage.width;
				var sy = info.windowHeight / Laya.stage.height;
				let tstlye = {left: _style.left*sx,top: _style.top*sy,width: _style.width*sx};
				this.boxAd.style=tstlye;
			}
		}
    }

    public hideBoxAd(){
        if(this.boxAd){
            this.boxAd.hide();
        }
    }

    private  nativeAd;
    public  getNativeAd(func:Function,_index:number=1){
        //console.log("getNativeAd1");
        if(this.sdkEnvironment){
            if(this.nativeAd){
                this.nativeAd.destroy();
                this.nativeAd=null;
            }
          
            let tid=SdkConf.getNatvieId(this.plafrom)
            this.nativeAd = this.sdkEnvironment.createNativeAd({
                posId: tid
            })
            this.nativeAd.onError((err)=> {
                func(null);
            })
            // let self= this
            //console.log("getNativeAd4");
            this.nativeAd.onLoad((res)=> {
                //console.log("getNativeAd5");
                func(res.adList);
                //WeiXinMgr.logTest('getNativeAd6', res.adList[0]);
            })
            this.nativeAd.load();
        }else{
            func([])
        }
    }

    public hasShortcutInstalled(func:Function){
        if(this.sdkEnvironment){
            this.sdkEnvironment.hasShortcutInstalled({
                success: function(res) {
                    // 判断图标未存在时，创建图标
                    func(res)
                },
                fail: function(err) { func(false)},
                complete: function() {}
            })
        }
    }

    public installShortcut(func:Function){
        if(this.getSdkEnvironment){
            this.sdkEnvironment.installShortcut({
                success: function() {
                    if(func)func();
                    console.log("installShortcutsuccess")
                },
                fail: function(err) {console.log("installShortcutFial",err)},
                complete: function() {}
            })
        }
    }
    
    public share (title?:any,msg=""){
        if(this.plafrom=="wx"){
            if(!title)title = SdkConf.shareDes;
            this.sdkEnvironment.shareAppMessage({
                title: title,
                imageUrlId: SdkConf.shareImgId,
                imageUrl: SdkConf.shareImgUrl,
                query:msg
              })
        }
    }

    public startRecord(_time:number=60,_frameRate:number=12){
        if(this.gameRecorder){
            this.gameRecorder.start({
                duration: _time,
                frameRate:_frameRate
            })

        }
    }

    public stopRecording(){
        if(this.gameRecorder){
            this.gameRecorder.stop();

        }
    }

    public shareRecordVideo(_func:Function=null){
        if(this.sdkEnvironment){
            if(!this.mVideoPath){
                if(_func)_func(2);
                return;
            }
            this.sdkEnvironment.shareAppMessage({
                channel: 'video',
                title: SdkConf.gameName,
                desc: SdkConf.shareDes,
                imageUrl: SdkConf.shareImgUrl,
                query: '',
                extra: {
                    videoPath: this.mVideoPath, // 可用录屏得到的视频地址
                    videoTopics: [SdkConf.shareDes],
                    withVideoId: true
                },
                success() {
                   if(_func)_func(0)
                },
                fail(e) {
                    if(_func)_func(1)
                }
            })
        }
    }

    public openGame(data,func?:any,path?:string,extraData?:any){
        if(this.plafrom=="wx"){
            this.sdkEnvironment.navigateToMiniProgram({
                appId: data.appId,
                path: path,
                extraData: extraData,
                envVersion: 'release',
                success(res) {
                    if(func)func(res);
                }
              })
        }
    }

    public isLongScene(){
        return Laya.stage.height/Laya.stage.width>=2.1;
    }

    public get isWeb(){
        return this.plafrom=="web";
    }

    public setStorage(data:any,key?:string){
        let tkey=key;
        if(!tkey)tkey=SdkConf.storageKey;
        if(this.sdkEnvironment){
            this.sdkEnvironment.setStorage({
                key:tkey,
                data:data
            })
        }else{
            Laya.LocalStorage.setItem(tkey,JSON.stringify(data));
        }
    }

    public getStorage(func:Function,key?:string){
        let tkey=key;
        if(!tkey)tkey=SdkConf.storageKey;
        let tdata;
        if(this.sdkEnvironment){
            this.sdkEnvironment.getStorage({
                key: tkey,
                success (res) {
                  if(func)func(res.data)
                },
                fail(res){
                    tdata = Laya.LocalStorage.getItem(tkey);
                    if(tdata)tdata = JSON.parse(tdata);
                    if(func)func(tdata)
                }
              })

        }else{
            tdata = Laya.LocalStorage.getItem(tkey);
            if(tdata)tdata = JSON.parse(tdata);
            if(func)func(tdata)
        }
    }

    public removeStorage(func?:Function,key?:string){
        let tkey=key;
        if(!tkey)tkey=SdkConf.storageKey;
        if(this.sdkEnvironment){
            this.sdkEnvironment.removeStorage({
                key: tkey,
                success (res) {
                    if(func)func(res.data)
                  },
                  fail(res){
                      if(func)func(-1)
                  }
              })

        }else{
            Laya.LocalStorage.removeItem(tkey);
        }
    }

    public clearStorage(func?:Function){
        if(this.sdkEnvironment){
            this.sdkEnvironment.clearStorage({
                success (res) {
                    if(func)func(1)
                  },
                  fail(res){
                      if(func)func(-1)
                  }
            });
        }else{
            Laya.LocalStorage.clear();
			if(func)func(1)
        }
    }

    public showWeixinLoading(_data=null){
        let tdata = _data;
        if(!tdata)tdata={
            title:"加载中",
            mask:true
        };
        if(this.sdkEnvironment)this.sdkEnvironment.showLoading(tdata);
    }

    public hideWeixinLoading(){
        if(this.sdkEnvironment)this.sdkEnvironment.hideLoading();
    }

    public getOpenId(){
        
    }

    public getUserInfo(_func:Function){
        let tself = this;
        if(tself.sdkEnvironment){
            tself.sdkEnvironment.getSetting({
                success (res){
                  if (res.authSetting['scope.userInfo']) {//  
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    tself.getUserInfo2(_func)
                  }else{
                    tself.sdkEnvironment.authorize({
                        scope: 'scope.userInfo',
                        success () {
                            tself.getUserInfo2(_func)
                        },
                        fail(){
                            _func(null); 
                        }
                      })
                  }
                },
                fail(){
                    _func(null);
                }
              })
        }else{
            _func(null);
        }
    }

    private getUserInfo2(_func:Function){
        this.sdkEnvironment.getUserInfo({
            success: function(res) {
                  _func(res.userInfo)
            },
            fail:function(){
              _func(null); 
            }
          })
    }

    public getSdkEnvironment():any{
        let tins=null;
        if(Laya.Browser.onQGMiniGame){
            tins=Laya.Browser.window.qg;
            this.plafrom="oppo";
        }else if(Laya.Browser.onQQMiniGame){
            tins=Laya.Browser.window.qq;
            this.plafrom="qq";
        }else if(Laya.Browser.window.tt){
            tins=Laya.Browser.window.tt;
            this.plafrom="tt";
			this.gameRecorder=tins.getGameRecorderManager();
        }
        else if(Laya.Browser.window.wx){
            tins=Laya.Browser.window.wx;
            this.plafrom="wx";
        }
        return tins;
    }
    
    public static getIns(){
        if(!this._sdk)this._sdk=new Sdk();
        return this._sdk;
    }
  
}
